import cgi
import wsgiref.handlers
import os
import datetime

from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db

time_format = '%H:%M'
datetime_format = '%m/%d/%y ' + time_format

class User(db.Model):
  email = db.EmailProperty()

class Child(db.Model):
  name = db.StringProperty()
  naps = db.ListProperty(db.Key)
  

class Nap(db.Model):
  child = db.ReferenceProperty()
  childName = db.StringProperty()
  start = db.DateTimeProperty()
  end = db.DateTimeProperty()
  duration = db.IntegerProperty()
  type = db.StringProperty()
  notes = db.StringProperty()



class MainPage(webapp.RequestHandler):

  def buildSumNap(self, dayTotal, childName, start):
    sumNap = Nap()
    sumNap.dayDuration = round(dayTotal / 60.00, 2)
    sumNap.childName = childName
    sumNap.start = start
    sumNap.isSum = True
    return sumNap


  def get(self):
    user = users.get_current_user()
    if user:
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      self.redirect(users.create_login_url(self.request.uri))
      return

    u = User.get_by_key_name('email:' + user.email())

    naps = None
    newnaps = None
    if u:
      naps = db.Query(Nap).ancestor(u.key()).order('childName').order('start')
      newnaps = []
      curDate = None
      dayTotal = 0.00
      for nap in naps:
        if curDate != None and nap.start.date() != curDate:
          sumNap = self.buildSumNap(dayTotal, nap.childName, nap.start)
          newnaps.append(sumNap)
          dayTotal = 0
        dayTotal = nap.duration + dayTotal
        curDate = nap.start.date()
        newnaps.append(nap)

      if curDate:
        sumNap = self.buildSumNap(dayTotal, nap.childName, nap.start)
        newnaps.append(sumNap)

    template_values = {
      'naps': newnaps,
      'url': url,
      'url_linktext': url_linktext,
      'user': user
    }

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

    
class DeleteNaps(webapp.RequestHandler):
  def post(self):
    for key,val in self.request.POST.items():
      if key.startswith('delete_'):
        napKey = key.split('delete_')
        db.get(db.Key(napKey[1])).delete()
    self.redirect('/')

class AddNap(webapp.RequestHandler):
  def post(self):
    user = users.get_current_user()
    if not user:
      self.redirect(users.create_login_url(self.request.uri))
      return

    u = User.get_or_insert('email:' + user.email())
    childName = self.request.get('child')
    child = Child.get_or_insert(childName, parent=u, name=childName)
    nap = Nap(parent=child)
    nap.child = child.key()
    nap.childName = child.key().name()
    startDateStr = self.request.get('startDate')
    nap.start = datetime.datetime.strptime(startDateStr + ' ' + self.request.get('startTime'), datetime_format)
    endTimeStr = self.request.get('endTime')
    if endTimeStr != '':
      endTime = datetime.datetime.strptime(endTimeStr, time_format)
      if nap.start.time() < endTime.time():
        nap.end = datetime.datetime.strptime(startDateStr + ' ' + endTimeStr, datetime_format)
      else:
        nextDay = nap.start.date() + datetime.timedelta(days=1)
        nap.end = datetime.datetime(nextDay.year, nextDay.month, nextDay.day, endTime.hour, endTime.minute)
      nap.duration = (nap.end - nap.start).seconds / 60
    else:
      nap.duration = self.request.get('duration')
      nap.end = nap.start + nap.duration
    nap.type = self.request.get('type')
    nap.notes = self.request.get('notes')
    nap.put()
    self.redirect('/')

class ChildLookup(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if not user:
      self.redirect(users.create_login_url(self.request.uri))
      return

    u = User.get_by_key_name('email:' + user.email())

    if not u:
      return
    self.response.headers['Content-Type'] = 'text/plain'
    kids = db.Query(Child).ancestor(u.key()).filter('name >=', self.request.get('q')).order('name')
    names = ''
    for kid in kids:
      names = names + kid.name + '\n'
    self.response.out.write(names)

def main():
  application = webapp.WSGIApplication(
                                       [('/', MainPage),
                                        ('/addNap', AddNap),
                                        ('/deleteNap', DeleteNaps),
                                        ('/childLookup', ChildLookup)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()